﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using WebApi2b.Data;
using WebApi2b.Domain.Interface;

namespace WebApi2b.Domain.Impementation
{
    public class EfResPository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admin10086DbContext db;
        public EfResPository(Admin10086DbContext admin10086) 
        {
            db = admin10086;
        }
        private DbSet<T> _entity;

        public DbSet<T> Entity 
        {
            get 
            {
                if (_entity==null) 
                {
                    _entity = db.Set<T>();
                }

                return _entity;
            }
        }
        public IQueryable<T> Table 
        {
            get 
            {
                return Entity;
            }
        }


        public void Delete(T entity)
        {
            _entity.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.Id == id).FirstOrDefault();
            Delete(row);
        }

        public T GetById(int id)
        {
            return Entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            Entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entities)
        {
            Entity.RemoveRange(entities);
            db.SaveChanges();
        }
    }
}
